package com.fabriciojf.action;

import com.fabriciojf.controller.Action;
import com.fabriciojf.model.Author;
import com.fabriciojf.model.Category;
import com.fabriciojf.model.Post;
import com.fabriciojf.model.Status;
import com.fabriciojf.persistence.JpaPersistence;
import com.fabriciojf.persistence.JpaUtil;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Action
 *
 * @author Fabricio S Costa fabriciojf@gmail.com
 * @since 01/12/2009
 * @version 1.0
 */
public class SalvarPostagemAction implements Action {

    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String titulo = request.getParameter("titulo");
        String conteudo = request.getParameter("conteudo");
        int idCategoria = Integer.parseInt(request.getParameter("categoria"));
        int idStatus = Integer.parseInt(request.getParameter("status"));

        Status status = (Status) JpaUtil.getEntityManager().find(Status.class, idStatus);
        Category categoria = (Category) JpaUtil.getEntityManager().find(Category.class, idCategoria);
        Author autor = (Author) JpaUtil.getEntityManager().find(Author.class, 1);

        try {
            Post post = new Post(titulo, conteudo, status, categoria, autor);
            
            JpaPersistence.getInstance().save(post);

            response.sendRedirect("FrontController?action=ManutencaoPostagem");
        } catch (Exception ex) {
            response.sendRedirect("./erro.jsp?mensagem=" + ex.getMessage());
            ex.printStackTrace();
        }
    }
}